package com.zhentao.studyim.controller;

import com.zhentao.studyim.dto.ApiResponse;
import com.zhentao.studyim.dto.MessageDto;
import com.zhentao.studyim.dto.SendMessageRequest;
import com.zhentao.studyim.service.MessageService;
import com.zhentao.studyim.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 消息控制器
 * 处理消息相关的HTTP请求
 */
@RestController
@RequestMapping("/api/messages")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class MessageController {

    private final MessageService messageService;
    private final JwtUtil jwtUtil;

    /**
     * 发送消息
     * POST /api/messages/send
     */
    @PostMapping("/send")
    public ApiResponse<MessageDto> sendMessage(
            @RequestBody SendMessageRequest request,
            @RequestHeader("Authorization") String authHeader) {

        try {
            // 1. 从Authorization头中提取token
            String token = authHeader.replace("Bearer ", "");

            // 2. 从token中获取当前用户ID
            Long currentUserId = jwtUtil.getUserIdFromToken(token);

            // 3. 保存消息
            MessageDto message = messageService.sendMessage(currentUserId, request.getToUserId(), request.getContent());

            return ApiResponse.success(message);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取聊天历史记录
     * GET /api/messages/history/{toUserId}
     */
    @GetMapping("/history/{toUserId}")
    public ApiResponse<List<MessageDto>> getChatHistory(
            @PathVariable Long toUserId,                    // 路径参数
            @RequestHeader("Authorization") String authHeader) {  // 请求头参数

        try {
            // 1. 从Authorization头中提取token
            String token = authHeader.replace("Bearer ", "");

            // 2. 从token中获取当前用户ID
            Long currentUserId = jwtUtil.getUserIdFromToken(token);

            // 3. 查询聊天历史
            List<MessageDto> messages = messageService.getChatHistory(currentUserId, toUserId);

            return ApiResponse.success(messages);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 标记消息为已读
     * POST /api/messages/{messageId}/read
     */
    @PostMapping("/{messageId}/read")
    public ApiResponse<Void> markAsRead(@PathVariable Long messageId) {
        // 实现消息已读功能（这里简化处理）
        return ApiResponse.success(null);
    }

    /**
     * 标记会话为已读
     * POST /api/messages/session/{sessionId}/read
     */
    @PostMapping("/session/{sessionId}/read")
    public ApiResponse<Void> markSessionAsRead(
            @PathVariable Long sessionId,
            @RequestHeader("Authorization") String authHeader) {

        try {
            // 1. 从Authorization头中提取token
            String token = authHeader.replace("Bearer ", "");

            // 2. 从token中获取当前用户ID
            Long currentUserId = jwtUtil.getUserIdFromToken(token);

            // 3. 标记与指定用户的会话为已读（这里sessionId实际上是对方用户ID）
            // 在实际项目中，这里可以实现更复杂的已读状态管理
            // 比如更新数据库中的已读状态、通知对方等

            return ApiResponse.success(null);
        } catch (Exception e) {
            return ApiResponse.error("标记会话已读失败: " + e.getMessage());
        }
    }
}